// filename: frontend/src/store/auth.js

import { defineStore } from "pinia";
import { computed, ref, reactive } from "vue";
import { request } from "@/utils/request";

export const useAuthStore = defineStore("auth", () => {
  const access_token = ref(uni.getStorageSync("access_token") || null);
  const refresh_token = ref(uni.getStorageSync("refresh_token") || null);
  const user = ref(JSON.parse(uni.getStorageSync("user_info") || "null"));
  
  const unreadCounts = reactive({
    messages: 0,
    notifications_interactions: 0,
    notifications_system: 0,
  });

  const isLoggedIn = computed(() => !!access_token.value && !!user.value);
  const totalUnreadNotifications = computed(() => unreadCounts.notifications_interactions + unreadCounts.notifications_system);
  const totalUnreadAll = computed(() => unreadCounts.messages + totalUnreadNotifications.value);

  const refreshToken = () => {
      if (!refresh_token.value) {
        clearAuth(false);
        return Promise.reject("No refresh token");
      }

      const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

      return new Promise((resolve, reject) => {
        uni.request({
          url: `${API_BASE_URL}/api/refresh`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${refresh_token.value}`
          },
          success: (res) => {
            // --- 【核心修改】 ---
            if (res.statusCode === 200 && res.data.access_token) {
              const newAccessToken = res.data.access_token;
              access_token.value = newAccessToken;
              uni.setStorageSync("access_token", newAccessToken);
            
              // 检查后端是否返回了新的 refresh_token
              if (res.data.refresh_token) {
                const newRefreshToken = res.data.refresh_token;
                refresh_token.value = newRefreshToken; // 更新 state
                uni.setStorageSync("refresh_token", newRefreshToken); // 更新本地存储
                console.log("🔄 Refresh token has been rotated.");
              }
            
              console.log("✅ Access token refreshed successfully.");
              resolve(newAccessToken);
            } else {
              console.error("❌ Failed to refresh token, logging out.");
              clearAuth();
              reject(res.data.error || "Refresh failed");
            }
          },
          fail: (err) => {
            console.error("❌ Network error during token refresh, logging out.");
            clearAuth();
            reject(err);
          }
        });
      });
  };
  
  const fetchTotalUnreadCounts = async () => {
    if (!isLoggedIn.value) {
      resetUnreadCounts();
      updateTabBarBadge();
      return;
    }

    try {
      const data = await request({
        url: '/api/me/unread-counts',
        method: 'GET'
      });
      
      if (data) {
        unreadCounts.messages = data.messages || 0;
        unreadCounts.notifications_interactions = data.notifications_interactions || 0;
        unreadCounts.notifications_system = data.notifications_system || 0;
        updateTabBarBadge();
      }
    } catch (error) {
      console.warn("Could not fetch unread counts:", error);
    }
  };
  
  const updateTabBarBadge = () => {
    if (totalUnreadAll.value > 0) {
      uni.setTabBarBadge({
        index: 3,
        text: String(totalUnreadAll.value)
      });
    } else {
      uni.removeTabBarBadge({
        index: 3
      });
    }
  };
  
  const resetUnreadCounts = () => {
      unreadCounts.messages = 0;
      unreadCounts.notifications_interactions = 0;
      unreadCounts.notifications_system = 0;
  };

  const setAuth = (newAccessToken, newRefreshToken, userInfo) => {
    access_token.value = newAccessToken;
    refresh_token.value = newRefreshToken;
    user.value = userInfo;
    uni.setStorageSync("access_token", newAccessToken);
    uni.setStorageSync("refresh_token", newRefreshToken);
    uni.setStorageSync("user_info", JSON.stringify(userInfo));
    fetchTotalUnreadCounts();
    window.location.reload();
  };
  
  const updateUserProfile = (newProfileData) => {
    if (user.value) {
      user.value = { ...user.value, ...newProfileData };
      uni.setStorageSync("user_info", JSON.stringify(user.value));
    }
  };

  const clearAuth = (shouldReload = true) => {
    access_token.value = null;
    refresh_token.value = null;
    user.value = null;
    uni.removeStorageSync("access_token");
    uni.removeStorageSync("refresh_token");
    uni.removeStorageSync("user_info");
    resetUnreadCounts();
    updateTabBarBadge();
    if (shouldReload) {
      window.location.reload();
    }
  };

  return {
    access_token,
    refresh_token,
    user,
    isLoggedIn,
    unreadCounts,
    totalUnreadNotifications,
    totalUnreadAll,
    fetchTotalUnreadCounts,
    setAuth,
    refreshToken,
    updateUserProfile,
    clearAuth,
  };
});